package com.apes.enquiry.supplier.santouliubi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.orderForm.model.OrderForm;
import com.apes.enquiry.orderForm.service.OrderFormService;
import com.apes.enquiry.supplier.santouliubi.SantouService;
import com.apes.enquiry.supplier.santouliubi.SantouliubiApi;
import com.apes.enquiry.supplier.santouliubi.model.SantouOrder;
import com.apes.enquiry.supplier.santouliubi.model.ShopManagement;
import com.apes.enquiry.supplier.santouliubi.repository.SantouEnquiryRepository;
import com.apes.enquiry.supplier.santouliubi.repository.SantouOrderRepository;
import com.apes.enquiry.supplier.santouliubi.repository.ShopManagementRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * 类描述：
 *
 * @ClassName SantouEnquiry
 * @Description 描述
 * @Author wushilong
 * @Date 2022/12/14 16:51
 * @Version 1.0
 */
@Service
public class SantouEnquiryService extends DomainService {

    @Autowired
    private SantouliubiApi santouliubiApi;

    @Autowired
    private SantouService santouService;

    @Autowired
    private SantouEnquiryRepository santouEnquiryRepository;

    @Autowired
    private ShopManagementRepository shopManagementRepository;

    @Autowired
    private ShopManagementService shopManagementService;

    @Autowired
    private SantouOrderRepository santouOrderRepository;

    @Autowired
    private OrderFormService orderFormService;


    /**
     * 获取三头六臂商品信息（匹配车型）
     * @param request
     * @return
     */
    public JSONObject vinSantouProductData(SimpleRequest request){
        JSONObject requestJO = request.getJO();
        if (org.apache.commons.lang3.StringUtils.isEmpty(requestJO.getJSONObject("partsTag").getString("name")))return new JSONObject();
        //获取门店在三头六臂的门店编号
        ShopManagement shopManagement = shopManagementRepository.findByStoreIdAndSantouIdNotNull(requestJO.getString("deptId"));
        //获取对应的三头六臂产品品类
        List categoryAll = santouEnquiryRepository.findLikeSantouId("%"+requestJO.getJSONObject("partsTag").getString("name")+"%");

        //获取三头六臂商品数据
        JSONObject result = santouService.vinQueryProduct(shopManagement, requestJO.getString("carExternalNumber"), categoryAll);

        //带上渠道区分区域
        result.put("merchantsId", shopManagement.getChannelNumber());

        return result;
    }

    /**
     * 获取三头六臂商品信息（有库存）
     *
     * @param request
     * @return
     */
    public JSONObject santouProductData(SimpleRequest request){
        JSONObject requestJO = request.getJO();
        //获取三头六臂产品编号
        JSONArray productNumber = requestJO.getJSONArray("productNumber");

        //三头六臂接口最多接受100个
        List productNumbers = astrictMaximum(productNumber);

        //获取三头门店管理
        ShopManagement shopManagement = shopManagementService.getOneShopManagement(requestJO.getString("deptId"));

        if (Objects.isNull(shopManagement)) return new JSONObject();

        //获取三头六臂商品数据
        JSONObject result = santouService.queryProduct(shopManagement, productNumbers, requestJO.getInteger("page"), requestJO.getInteger("size"));

        //带上渠道区分区域
        result.put("merchantsId", shopManagement.getChannelNumber());

        return result;
    }

    private List astrictMaximum(JSONArray productNumber){
        if (productNumber.size() > 100){
           return productNumber.subList(0, 99);
        }
        return productNumber;
    }

    /**
     * 向三头六臂下订单
     *
     *
     */
    public JSONObject orderForm(OrderForm orderForm, JSONArray productRequireItems) {
        //商品列表（商品+数量）
        JSONArray products = new JSONArray();
        productRequireItems.forEach(item -> {
            JSONObject detail = (JSONObject) item;
            if (StringUtils.isEmpty(detail.getString("channelType")) || detail.getInteger("channelType") != 4) return;
            JSONObject data = new JSONObject();
            data.put("productNumber",detail.getString("spId"));
            data.put("quantity", detail.getIntValue("distributionQty"));
            products.add(data);
        });
        if (products.isEmpty()) return new JSONObject();

        //三头六臂门店编号
        ShopManagement shopManagement = shopManagementRepository.findByStoreIdAndSantouIdNotNull(orderForm.getClientId());


        //拼装三头六臂请求数据
        JSONObject params = new JSONObject();
        params.put("merchantsId", shopManagement.getChannelNumber());//渠道商id
        params.put("relatedNumber", orderForm.getId());//订单单号
        params.put("items", products);//商品+数量
        String remark = productRequireItems.getJSONObject(0).getString("remark");
        if (Objects.nonNull(remark) || Objects.nonNull(orderForm.getVIN()))params.put("note", remark+" 车架号："+ orderForm.getVIN());//备注
        params.put("garageNumber",shopManagement.getSantouId());//三头门店编号
        //调用三头六臂接口
        JSONObject pretty = santouliubiApi.orderForm(params);
        JSONObject result = pretty.getJSONObject("result");

        //记录三头六臂订单创建记录(三头六臂回调需要用到)
        newSantouLog(productRequireItems.getJSONObject(0), shopManagement, result, orderForm.getId());
        return pretty;
    }

    /**
     * 同一张要货单只能向三头六臂下一张订单,请求单号+渠道商是惟一的
     * @param id
     * @return 请求三头六臂的单号
     */
    private String getOrderNumber(String id){
        int i = id.indexOf("-");//示例：YH1001230210806-a
        if (i<0) return id + "-a";//第一次没有
        String suffix = id.substring(i+1);
        id = id.substring(0, i);
        int hashCode = suffix.hashCode() + 1;
        char suffix1 = (char) hashCode;
        return id+"-"+suffix1;
    }

    /**
     * 记录三头六臂订单创建记录
     * @param require 请求对象
     * @param shopManagement 三头门店管理
     * @param result 三头返回结果
     */
    private void newSantouLog(JSONObject require, ShopManagement shopManagement, JSONObject result, String orderNumber) {
        //记录三头六臂订单创建记录
        if (Objects.nonNull(result)){
            SantouOrder santouOrder = new SantouOrder();
            santouOrder.setId(result.getString("orderNumber"));
            santouOrder.setOrderNumber(orderNumber);
            santouOrder.setRelatedNumber(require.getString("productRequireId"));
            santouOrder.setStatus(result.getString("status"));
            santouOrder.setStatusName(result.getString("statusName"));
            santouOrder.setStoreId(shopManagement.getStoreId());
            santouOrder.setSantouId(shopManagement.getSantouId());
            santouOrder.setSummary(result.getString("summary"));
            santouOrderRepository.saveAndFlush(santouOrder);
        }
    }

    /**
     * 三头六臂取消订单
     * @param json
     * @return
     */
    public JSONObject cancelOrder(JSONObject json){
        SantouOrder santouOrder = santouOrderRepository.findOne(json.getJSONObject("data").getString("orderNumber"));
        if (!santouOrder.getStatus().equals("5")) {
            santouOrder.setReason("订单已受理！");
            santouOrderRepository.saveAndFlush(santouOrder);
            return null;
        }

        SimpleRequest request = new SimpleRequest();
        JSONObject user = getUser();
        request.setData(MapUtil.mapper("id", santouOrder.getOrderNumber(), "user", user));

        //取消订单，已分配数归零。流入要货补货管理
        OrderForm orderForm = orderFormService.cancelOrderForm(request);
        if (Objects.nonNull(orderForm)){
            santouOrder.setStatusName("已取消");
            santouOrder.setStatus("40");
            santouOrderRepository.saveAndFlush(santouOrder);
            //返回三头六臂接收成功格式
            return SantouService.getJsonObject("已取消");
        }
        //记录原因
        santouOrder.setReason("订单取消失败！");
        santouOrderRepository.saveAndFlush(santouOrder);
        return null;
    }

    //回调确认人默认是系统
    private JSONObject getUser(){
        JSONObject param = new JSONObject();
        param.put("id", "9430");
        param.put("name", "系统");
        return param;
    }

    /**
     * 三头六臂确认订单
     * @param json
     * @return
     */
    public JSONObject newOrder(JSONObject json){
        SantouOrder santouOrder = santouOrderRepository.findOne(json.getJSONObject("data").getString("orderNumber"));
        if (!santouOrder.getStatus().equals("5")) {
            santouOrder.setReason("订单已受理！");
            santouOrderRepository.saveAndFlush(santouOrder);
            return null;
        }

        SimpleRequest request = new SimpleRequest();
        JSONObject user = getUser();
        request.setData(MapUtil.mapper("id", santouOrder.getOrderNumber(), "user", user));
        //生成已审核的采购订单
        OrderForm orderForm = orderFormService.affirmOrderForm(request);
        OrderForm shipments = orderFormService.shipments(request);
        if (Objects.nonNull(orderForm) && Objects.nonNull(shipments)){
            santouOrder.setStatusName("待收货");
            santouOrder.setStatus("10");
            santouOrderRepository.saveAndFlush(santouOrder);
            //返回三头六臂接收成功格式
            return SantouService.getJsonObject("待收货");
        }
        //记录原因
        santouOrder.setReason("订单确认失败！");
        santouOrderRepository.saveAndFlush(santouOrder);
        return null;
    }

    public JSONObject test(JSONObject json){
        SantouOrder santouOrder = new SantouOrder();
        santouOrder.setId(json.getString("id"));
        santouOrder.setStatusName("待收货");
        santouOrder.setStatus("10");
        santouOrder.setSantouId(json.getString("id"));
        santouOrder.setStoreId("123456");
        santouOrderRepository.saveAndFlush(santouOrder);
        return SantouService.getJsonObject("待收货");
    }

    /**
     * 确认收货
     * @param supplierRef
     */
    public JSONObject santouReceipt(String supplierRef){
        SantouOrder santouOrder = santouOrderRepository.findOne(supplierRef);
        ShopManagement shopManagement = shopManagementRepository.findByStoreIdAndSantouIdNotNull(santouOrder.getStoreId());
        JSONObject params = new JSONObject();
        params.put("merchantsId", shopManagement.getChannelNumber());//渠道商id
        params.put("orderNumber", santouOrder.getId());//单据号
        params.put("garageNumber",santouOrder.getSantouId());//三头门店编号
        //调用三头六臂接口
        JSONObject pretty = santouliubiApi.receipt(params);
        JSONObject result = pretty.getJSONObject("result");
        if (Objects.nonNull(result)){
            santouOrder.setStatusName("已完成");
            santouOrder.setStatus("30");
        }
        return result;
    }

    /**
     * 自动收货
     * @param json
     * @return
     */
    public JSONObject confirmReceipt(JSONObject json){
        JSONObject data = json.getJSONObject("data");
        SantouOrder santouOrder = santouOrderRepository.findOne(data.getString("orderNumber"));
        if (Objects.isNull(santouOrder)){
            return null;
        }
        String voucherURL = data.getString("signVoucher");
        //获取三头收货凭证
        if (StringUtils.isEmpty(voucherURL)){
            santouOrder.setReason("未获取到凭证，收货失败！");
            santouOrderRepository.saveAndFlush(santouOrder);
            return null;
        }

        santouOrder.setSignVoucherURL(voucherURL);
        //通知ERP平台收货
        JSONObject result = JSON.parseObject(invoke("stock.santouPurchaseOrderService.confirmReceipt", santouOrder));
        //收货成功
        if (result.getBoolean("body")){
            santouOrder.setStatusName("已收货");
            santouOrder.setStatus("30");
            santouOrderRepository.saveAndFlush(santouOrder);
            //返回三头六臂接收成功格式
            return SantouService.getJsonObject("已收货");
        }
        //返回三头六臂接收成功格式
        return null;
    }


}
